package com.mdp.workflow.ru.ctrl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mdp.core.entity.Result;
import com.mdp.core.err.BizException;
import com.mdp.core.query.QueryTools;
import com.mdp.core.utils.ObjectTools;
import com.mdp.core.utils.RequestUtils;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.utils.LoginUtils;
import com.mdp.swagger.ApiEntityParams;
import com.mdp.workflow.pub.service.SysUserService;
import com.mdp.workflow.ru.entity.Task;
import com.mdp.workflow.ru.service.TaskServiceImpl;
import com.mdp.workflow.ru.vo.TaskCandidateVo;
import com.mdp.workflow.ru.vo.TaskCompleteVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value="/**/ru/task")
@Api(tags={"act_ru_task-操作接口"})
public class TaskController {
	
	static Logger logger =LoggerFactory.getLogger(TaskController.class);
	
	@Autowired
	private TaskServiceImpl taskService;

	@Value(value = "${mdp.platform-branch-id:platform-branch-001}")
	String platformBranchId;
	
	@Autowired
	private SysUserService sysUserService;

	@ApiOperation( value = "act_ru_task-查询列表",notes=" ")
	@ApiEntityParams(Task.class)
	@ApiResponses({
		@ApiResponse(code = 200,response=Task.class,message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'错误码'},total:总记录数,data:[数据对象1,数据对象2,...]}")
	})
	@RequestMapping(value="/list",method=RequestMethod.GET)
	public Result listTask(@ApiIgnore @RequestParam Map<String,Object> params){
		try {

			RequestUtils.transformArray(params, "categoryIds");
			RequestUtils.transformArray(params, "tagIds");
			RequestUtils.transformArray(params, "procInstIds");
			User user=LoginUtils.getCurrentUserInfo();
			QueryWrapper<Task> qw = QueryTools.initQueryWrapper(Task.class , params).in("res.tenant_id_",user.getBranchId(),platformBranchId);
			IPage page=QueryTools.initPage(params);
			List<Map<String,Object>> datas = taskService.selectListMapByWhere(page,qw,params);
			datas=assigneeUsernameTran(datas);
			return Result.ok("query-ok","查询成功").setData(datas).setTotal(page.getTotal());
		}catch (BizException e) {
			return Result.error(e);
		}catch (Exception e) {
			return Result.error(e);
		}
	}
	
 

	@ApiOperation( value = "act_ru_task-根据主键查询一条数据",notes=" ")
     @ApiResponses({
            @ApiResponse(code = 200,response=Task.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")
    })
    @RequestMapping(value="/queryById",method=RequestMethod.GET)
    public Result queryById(Task task) {
        Task data = (Task) taskService.getById(task);
        return Result.ok().setData(data);
    }

	/**
	 * 请求,如list
	 * 分页参数 {currentPage:1,pageSize:10,total:0}
	 * 根据条件查询数据对象列表,如果不上传分页参数，将不会分页。后台自动分页，无需编程
	 * taskType 0已领取待执行的任务，1待领取的个人业务,2待领取的部门业务
	 */
	@RequestMapping(value="/listAssigneeToAnyTasks")
	public Result listAssigneeToAnyTasks( @RequestParam Map<String,Object> params){
 		return listTask(params);
	}
	public List<Map<String,Object>> assigneeUsernameTran(List<Map<String,Object>> datas){
		if(datas==null ||datas.size()==0){
			return datas;
		}else{//assignee_,'' assignee_name
			List<String> userids=datas.stream().map(i->(String)i.get("assignee")).collect(Collectors.toList());
			Map<String,String> usersMap=this.sysUserService.selectUserMapForSimpleInfoByUserids(userids);
			for (Map<String, Object> data : datas) {
				data.put("assigneeName",usersMap.get(data.get("assignee")));
			}
			return datas;
		}
	}
	/**
	 * 请求,如list
	 * 分页参数 {currentPage:1,pageSize:10,total:0}
	 * 根据条件查询数据对象列表,如果不上传分页参数，将不会分页。后台自动分页，无需编程
	 * taskType 0已领取待执行的任务，1待领取的个人业务,2待领取的部门业务
	 */
	@RequestMapping(value="/listAssigneeToMeTasks")
	public Result listAssigneeToMeTasks( @RequestParam Map<String,Object> params){

		User user=LoginUtils.getCurrentUserInfo();
		if(params.containsKey("assignee") && user.getUserid().equals(params.get("assignee"))) {//如果是只查询本人相关的
			return listTask(params);
		}else if(!params.containsKey("assignee")){
			return Result.error("没有指定执行用户编号assignee，不允许查询");
		} else if(!user.getUserid().equals(params.get("assignee"))){
			return Result.error("不允许查询别人的任务");
		}

		return Result.ok();
	}

	/**
	 * 请求,如list
	 * 分页参数 {currentPage:1,pageSize:10,total:0}
	 * 根据条件查询数据对象列表,如果不上传分页参数，将不会分页。后台自动分页，无需编程
	 * taskType 0已领取待执行的任务，1待领取的个人业务,2待领取的部门业务
	 */
	@RequestMapping(value="/listMyCandidateUserTasks")
	public Result listMyCandidateUserTasks( @RequestParam Map<String,Object> params){

		User user=LoginUtils.getCurrentUserInfo();
		params.put("candidateUser",user.getUserid());
		params.put("hxRoleids", Arrays.stream(LoginUtils.getMyRoleids()).collect(Collectors.joining(",")));
		params.put("hxDeptids",user.getDeptid());
		return this.listAnyCandidateUserTasks(params);

	}

	public List<Map<String,Object>> tranFlowableTaskToMap(List<org.flowable.task.api.Task> atasks) {
		List<Map<String,Object>> mapList=new ArrayList<>();
		for (org.flowable.task.api.Task task : atasks) {
			Map<String,Object> taskMap=new HashMap<>();
			taskMap.put("procDefId", task.getProcessDefinitionId());
			taskMap.put("executionId", task.getProcessDefinitionId());
			taskMap.put("procInstId", task.getProcessDefinitionId());
			taskMap.put("taskDefId", task.getProcessDefinitionId());
			taskMap.put("taskDefKey", task.getProcessDefinitionId());
			taskMap.put("tenantId", task.getProcessDefinitionId());
			taskMap.put("createTime", task.getProcessDefinitionId());
			taskMap.put("owner", task.getProcessDefinitionId());
			taskMap.put("assignee", task.getProcessDefinitionId());
			taskMap.put("parentTaskId", task.getProcessDefinitionId());
			taskMap.put("description", task.getProcessDefinitionId());
			taskMap.put("rev", task.getProcessDefinitionId());
			taskMap.put("id", task.getProcessDefinitionId());
			taskMap.put("processDefinitionId", task.getProcessDefinitionId());
			mapList.add(taskMap);
		}
		return mapList;
	}


	/**
	 * 请求,如list
	 * 分页参数 {currentPage:1,pageSize:10,total:0}
	 * 根据条件查询数据对象列表,如果不上传分页参数，将不会分页。后台自动分页，无需编程
	 * taskType 0已领取待执行的任务，1待领取的个人业务,2待领取的部门业务
	 */
	@RequestMapping(value="/listAnyCandidateUserTasks")
	public Result listAnyCandidateUserTasks( @RequestParam Map<String,Object> params){
 			params.put("linkType","candidate");
			List<String> candidateGroups=new ArrayList<>();
			String hxRoleids= (String) params.get("hxRoleids");
			 if(ObjectTools.isNotEmpty(hxRoleids)){
				 for (String g : hxRoleids.split(",")) {
					 candidateGroups.add("_role_"+g);
				 }
			 }
			String hxPostids= (String) params.get("hxPostids");
			if(ObjectTools.isNotEmpty(hxPostids)){
				for (String g : hxPostids.split(",")) {
					candidateGroups.add("_post_"+g);
				}
			}
			String hxDeptids= (String) params.get("hxDeptids");
			if(ObjectTools.isNotEmpty(hxDeptids)){
				for (String g : hxDeptids.split(",")) {
					candidateGroups.add("_dept_"+g);
				}
			}
			params.put("candidateGroups",candidateGroups);
			return listTask(params);
	}


	/**
	 * 新增候选人/部门/岗位 {taskId:'',procInstId:'',userids:[userid],groupIds:[],postIds:[]}
	 */
	@RequestMapping(value="/addCandidate")
	public Result addCandidate(@RequestBody TaskCandidateVo candidateVo) {
		try{
			return taskService.addCandidate(candidateVo);
		}catch (BizException e) {
			logger.error("执行异常",e);
			return Result.error(e);
		}catch (Exception e) {
			logger.error("执行异常",e);
			return Result.error(e.getMessage());
		}
	}

	/**
	 * 查询候选人 params:{taskId:'',procInstId:''}
	 */
	@RequestMapping(value="/listCandidate")
	public Result listCandidate( @RequestParam Map<String,Object> params){
		if(params.containsKey("taskId") ) {//如果是只查询本人相关的
			params.remove("tenantId");
			List<Map<String,Object>> datas=taskService.listCandidates(params);
			TaskCandidateVo candidateVo=new TaskCandidateVo();
			candidateVo.setHxUserids(datas.stream().map(k->(String)k.get("userId")).filter(k->ObjectTools.isNotEmpty(k)).collect(Collectors.joining(",")));
			List<String> groupIds=datas.stream().map(k->(String)k.get("groupId")).filter(k->ObjectTools.isNotEmpty(k)).collect(Collectors.toList());
			candidateVo.setHxRoleids(groupIds.stream().filter(k->k.startsWith("_role_")).collect(Collectors.joining(",")));
			candidateVo.setHxPostids(groupIds.stream().filter(k->k.startsWith("_post_")).collect(Collectors.joining(",")));
			candidateVo.setHxDeptids(groupIds.stream().filter(k->k.startsWith("_dept_")).collect(Collectors.joining(",")));
			return Result.ok().setData(candidateVo);
		}else {
			return Result.error("没有指定任务编号taskId，不允许查询");
		}
	}

	/**
	 * 删除候选人/部门/岗位 {taskId:'',procInstId:'',userids:[userid],groupIds:[],postIds:[]}
	 */
	@RequestMapping(value="/delCandidate")
	public Result delCandidate(@RequestBody TaskCandidateVo candidateVo) {

		try{
			return taskService.delCandidate(candidateVo);
		}catch (BizException e) {
			logger.error("执行异常",e);
			return Result.error(e);
		}catch (Exception e) {
			logger.error("执行异常",e);
			return Result.error(e.getMessage());
		}
	}

	@Deprecated
	/**
	 * 请求,如list
	 * 分页参数 {currentPage:1,pageSize:10,total:0}
	 * 根据条件查询数据对象列表,如果不上传分页参数，将不会分页。后台自动分页，无需编程
	 * taskType 0已领取待执行的任务，1待领取的个人业务,2待领取的部门业务
	 */
	@RequestMapping(value="/listMyCandidateGroupTasks")
	public Result listMyCandidateGroupTasks( @RequestParam Map<String,Object> params){
 		 return listMyCandidateUserTasks(params);
	}

	@Deprecated
	/**
	 * 请求,如list
	 * 分页参数 {currentPage:1,pageSize:10,total:0}
	 * 根据条件查询数据对象列表,如果不上传分页参数，将不会分页。后台自动分页，无需编程
	 * taskType 0已领取待执行的任务，1待领取的个人业务,2待领取的部门业务
	 */
	@RequestMapping(value="/listAnyCandidateGroupTasks")
	public Result listAnyCandidateGroupTasks( @RequestParam Map<String,Object> params){
 		return listMyCandidateUserTasks(params);
	} 

	/**
	 * 新增一条数据
	 */
	@RequestMapping(value="/addComment")
	public Result addComment(@RequestBody Map<String,Object> comment) {

		try{
			String userid=(String) comment.get("userid");
			String taskId=(String)comment.get("taskId");
			String procInstId=(String)comment.get("procInstId");
			String commentMsg=(String)comment.get("commentMsg");
			if(org.apache.commons.lang3.StringUtils.isEmpty(commentMsg)) {
				return Result.error("commentMsg-no-value","commentMsg","办理意见不能为空");
			}
			if(org.apache.commons.lang3.StringUtils.isEmpty(taskId)) {
				return Result.error("taskId-no-value","taskId","任务编号不能为空");
			}
			if(org.apache.commons.lang3.StringUtils.isEmpty(procInstId)) {
				return Result.error("procInstId-no-value","procInstId","实例编号不能为空");
			}

			if(org.apache.commons.lang3.StringUtils.isEmpty(userid)) {
				return Result.error("userid-no-value","userid","用户编号不能为空");
			}
			taskService.addCommentMsg(userid, taskId, procInstId, commentMsg);
			return Result.ok();
		}catch (BizException e) {
			logger.error("执行异常",e);
			return Result.error(e);
		}catch (Exception e) {
			logger.error("执行异常",e);
			return Result.error(e.getMessage());
		}
	}
	/**
	 * 新增一条数据
	 */
	@RequestMapping(value="/complete")
	public Result complete(@RequestBody TaskCompleteVo taskCompleteVo) {

		try{
			return taskService.completeTask(taskCompleteVo);
		}catch (BizException e) {
			logger.error("执行异常",e);
			return Result.error(e);
		}catch (Exception e) {
			logger.error("执行异常",e);
			return Result.error(e.getMessage());
		}
	}

	@Deprecated
	/**
	 * 查询候选人 params:{taskId:'',procInstId:''}
	 */
	@RequestMapping(value="/listCandidateUsers")
	public Result listCandidateUsers( @RequestParam Map<String,Object> params){
		 return listCandidate(params);
	}

	/**
	 * 根据主键修改一条数据
	 */
	@RequestMapping(value="/edit")
	public Result editTask(@RequestBody Task task) {

		try{
			taskService.updateSomeFieldByPk(task);
			return Result.ok();
		}catch (BizException e) {
			logger.error("执行异常",e);
			return Result.error(e);
		}catch (Exception e) {
			logger.error("执行异常",e);
			return Result.error(e.getMessage());
		}
	}
}
